package com.zzjson.concurrency.loopthread;

import lombok.SneakyThrows;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author 霄池
 * @Date 2023/7/31 23:54
 */
public class LockThread {

    static ReentrantLock lock = new ReentrantLock();

    static Condition condition = lock.newCondition();

    static int num;

    public static void main(String[] args) {
        Thread threadA = new Thread(() -> {
            print(0);
        }, "A");

        Thread threadB = new Thread(() -> {
            print(1);
        }, "B");

        Thread threadC = new Thread(() -> {
            print(2);
        }, "C");

        threadA.start();

        threadB.start();

        threadC.start();

    }

    @SneakyThrows
    private static void print(int flag) {
        try {
            lock.lock();
            while (num % 3 != flag) {
                condition.await();
            }
            System.out.println(Thread.currentThread().getName());
            num++;
            condition.signal();
        } finally {
            lock.unlock();
        }

    }
}
